package kaist.sep521.lego.circlebicycle;

import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class RegisterActivity extends Activity {

	EditText id;
	EditText pw;
	EditText pw2;
	EditText nick;

	public static String checkIdUrl = "http://14.63.196.253/~lego/check_id.php";
	public static String signinUrl = "http://14.63.196.253/~lego/signin.php";

	private Handler mHandler;
	private Runnable mRunnable;

	// Alphabet + Number
	protected InputFilter filterAlphaNum = new InputFilter() {
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			Pattern ps = Pattern.compile("^[a-zA-Z0-9]+$");
			if (!ps.matcher(source).matches()) {
				return "";
			}
			return null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.permitNetwork().build());

		id = (EditText) findViewById(R.id.register_editID);
		pw = (EditText) findViewById(R.id.register_editPW);
		pw2 = (EditText) findViewById(R.id.register_confirmPW);
		nick = (EditText) findViewById(R.id.register_editNickname);

		id.setFilters(new InputFilter[] { filterAlphaNum });
		pw.setFilters(new InputFilter[] { filterAlphaNum });
		pw2.setFilters(new InputFilter[] { filterAlphaNum });
		nick.setFilters(new InputFilter[] { filterAlphaNum });

		final Button checkID = (Button) findViewById(R.id.register_checkID_button);
		final Button completeBtn = (Button) findViewById(R.id.register_complete_button);

		// Set up the user interaction to manually show or hide the system UI.
		checkID.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// check a validation of user
				String username = id.getText().toString();
				String result = checkId(username);

				if (result.equals("true")) {
					// move to menu window
					Toast.makeText(
							RegisterActivity.this,
							"The ID, "
									+ username
									+ " is already exist. Plese, Input another one.",
									Toast.LENGTH_SHORT).show();

				} else {

					Toast.makeText(RegisterActivity.this,
							"The ID, " + username + " is OK. :)",
							Toast.LENGTH_LONG).show();
				}

			}
		});

		// Set up the user interaction to manually show or hide the system UI.
		completeBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// check a validation of user
				String username = id.getText().toString();
				String password = pw.getText().toString();
				String password2 = pw2.getText().toString();
				String nickname = nick.getText().toString();

				if (password.equals(password2)) {

					String result = signin(username, password, nickname);

					if (result.equals("true")) {
						Toast.makeText(RegisterActivity.this,
								"Sign In success. Please, Log in. :)",
								Toast.LENGTH_SHORT).show();

						mRunnable = new Runnable() {
							@Override
							public void run() {
								// move to login window
								Intent intent = new Intent(getBaseContext(),
										MainActivity.class);
								startActivity(intent);
							}
						};

						mHandler = new Handler();
						mHandler.postDelayed(mRunnable, 1500);

					} else {
						Toast.makeText(RegisterActivity.this, "Fail to regist!!",
								Toast.LENGTH_SHORT).show();
					}

				} else {
					Toast.makeText(RegisterActivity.this,
							"Password doesn't match. Please, input again..",
							Toast.LENGTH_SHORT).show();
				}

			}
		});

	}

	private String checkId(String username) {
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(checkIdUrl);
		try {
			// Add user name and password
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user", username));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
			String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

			if (str.toString().equalsIgnoreCase("true")) {
				return ("true");
			} else {
				return ("false");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ("OK");

	}

	private String signin(String username, String password, String nickname) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(signinUrl);
		try {
			String phoneNumber = "01000001234";

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user", username));
			nameValuePairs.add(new BasicNameValuePair("pass", password));
			nameValuePairs.add(new BasicNameValuePair("nick", nickname));
			nameValuePairs.add(new BasicNameValuePair("phone", phoneNumber));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

			if (str.toString().equalsIgnoreCase("true")) {
				return ("true");
			} else {
				return (str);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ("OK");

	}

}
